import { get } from "../../utils/db.js"
Page({
  data: {
    keyword: '',
    list: [],//热门搜索
    history: []//历史搜索
  },
  myInput(e) {
    this.data.keyword = e.detail.value
  },
  onShow() {
    //读取缓存
    var history = wx.getStorageSync("history") || []
    this.setData({
      history
    })
  },
  async onLoad() {
    //读取最高10条
    var result = await get('menu', {}, 0, 6, { field: 'views', sort: 'desc' })
    this.setData({
      list: result.data
    })
  },
  // 搜索
  doSearch() {    // 点击跳转list
    var arr = wx.getStorageSync("history") || [];
    var index = arr.findIndex(item => {
      return item == this.data.keyword  //判断是否存在没有return -1
    })
    if (index == -1) {
      arr.unshift(this.data.keyword)
    } else {
      //删除已经存在的；添加新来的
      arr.splice(index, 1)
      arr.unshift(this.data.keyword)
    }
    wx.setStorageSync("history", arr)
    wx.navigateTo({
      url: '/pages/list/list?keyword=' + this.data.keyword,
    })
  },
  toDetail(e) {  //条详情页
    var id = e.currentTarget.id;
    wx.navigateTo({
      url: '/pages/detail/detail?id=' + id,
    })
  },
  //跳转list页面
  toList(e){
	  var keyword=e.currentTarget.dataset.keyword;
	  wx.navigateTo({
		  url:"/pages/list/list?keyword="+keyword
	  })
  }
})